// 主js  业务相关函数
"use strict";
// 描述页面状态
let pageStatus = {
	hash: "", // #/shortmessage #/signup或空
	// 登录信息状态
	logion: {
		userName: false,
		password: false,
		remember: false,
		// 短信登录
		phone: false,
		vCode: false
	},
	// 注册页面
	signup: {
		name: false,
		domain: false,
		phoneOrEmail: false,
		vCode: false,
		password: false,
		agree: false
	}
};
// 路由
function router() {
	const hash = location.hash;
	pageStatus.hash = hash;
	function normalLogin() {
		// 输入框
		sys.getEl(".normalLogin").style.display = "block";
		sys.getEl(".loginBranch").style.display = "block";
		sys.getEl(".signupBranch").style.display = "none";
		// 跳转按钮
		sys.getEl(".changeNormalLogin").style.display = "none";
		sys.getEl(".shortmessageLogin").style.display = "none";
		sys.getEl(".changeShortmessageLogin").style.display = "block";
	}
	switch (hash) {
		case "":
			normalLogin();
			break;
		case "#/signup":
			sys.getEl(".loginBranch").style.display = "none";
			sys.getEl(".signupBranch").style.display = "block";
			break;
		case "#/shortmessage":
			sys.getEl(".loginBranch").style.display = "block";
			sys.getEl(".signupBranch").style.display = "none";
			sys.getEl(".normalLogin").style.display = "none";
			sys.getEl(".shortmessageLogin").style.display = "block";
			sys.getEl(".changeNormalLogin").style.display = "block";
			sys.getEl(".changeShortmessageLogin").style.display = "none";
			break;
		default:
			normalLogin();
			break;
	}
}
/**
 * @description 设置左侧评论
 * @author 衣沾不足惜 javascript.h@qq.com
 * @date 2020-05-03
 * @param data {name,tag,text}
 */
function setComment(data) {
	let [oName, oTag, oText] = [
		...sys.getEls(
			".randomBox .content .name,.randomBox .content .tag ,.randomBox .content .text "
		)
	];
	// content
	// {
	/* <div class="row nameAndTag">
<div class="name"></div>
<div class="tag"></div>
</div>
<div class="row text"></div> */
	// }
	oName.innerHTML = data.name;
	oTag.innerHTML = data.tag;
	oText.innerHTML = data.text;
}
/**
 * @description 设置随机评论
 * @author 衣沾不足惜 javascript.h@qq.com
 * @date 2020-05-03
 */
function setRandomComment() {
	let index = Math.floor(Math.random() * mockData.randomInfo.length);
	setComment(mockData.randomInfo[index]);
}
/**
 * @description 显示表单错误信息 , 自动选择兄弟元素errorInfo
 * @author 衣沾不足惜 javascript.h@qq.com
 * @date 2020-05-04
 * @param elSelector
 * @param msg
 */
function showFormError(elSelector, msg) {
	const el = sys.getEl(elSelector);
	// 对应的兄弟元素 错误提示
	sys.getEl(elSelector + "+ .errorInfo").style.display = "block";
	sys.getEl(elSelector + "+ .errorInfo").innerText = msg;
	//输入框自身变红
	if (el.tagName == "INPUT") {
		el.className = "inputError";
	}
}
/**
 * @description 隐藏表单错误信息
 * @author 衣沾不足惜 javascript.h@qq.com
 * @date 2020-05-04
 * @param elSelector
 * @param msg
 */
function hideFormError(elSelector) {
	const el = sys.getEl(elSelector);
	sys.getEl(elSelector + "+ .errorInfo").style.display = "none";
	sys.getEl(elSelector + "+ .errorInfo").innerText = "";
	if (el.tagName == "INPUT") {
		el.className = "";
	}
}
function countDown(elSelector, count = 60) {
	const el = sys.getEl(elSelector);
	if (el.countDownIng) return;
	el.countDownIng = true;
	sys.getEl(".vCodeBoxBody #sendVcode + .help").style.display = "block";
	let timer = setInterval(() => {
		if (count > 0) {
			el.innerText = `${count--}秒后可重发`;
		} else {
			clearInterval(timer);
			el.countDownIng = false;
			el.innerText = `重发验证码`;
		}
	}, 1000);
}
/**
 * @description 表单相关
 * @author 衣沾不足惜 javascript.h@qq.com
 * @date 2020-05-04
 */
function loginFormInit() {
	/*
	 *普通登录
	 */
	const oUserName = sys.getEl("#userName");
	const oPassword = sys.getEl("#password");
	const oRemember = sys.getEl("#remember");
	const oSubmitLogin = sys.getEl("#submitLogin");
	// 输入框值改变/失去焦点时执行
	function runUserName(e, elSelector) {
		let value = (oUserName.value = e.target.value.trim());
		if (!value) {
			showFormError(elSelector, "用户名为必填项");
			pageStatus.logion.userName = false;
			return;
		}
		// 原网站登录时未校验邮箱/个性域名/手机是否正确
		let userNameisTrue =
			checkPhone(value) ||
			checkEmail(value) ||
			checkUserdomainName(value);
		// 至少有一个正确
		if (userNameisTrue) {
			// 修改状态 / 隐藏错误信息 /隐藏登录失败
			pageStatus.logion.userName = true;
			hideFormError(elSelector);
			sys.getEl(".loginError").style.display = "none";
		} else {
			showFormError(elSelector, "手机、邮箱或个人空间地址错误");
			pageStatus.logion.userName = false;
		}
	}
	// userName
	oUserName.addEventListener(
		"input",
		debounce(function(e) {
			runUserName(e, "#userName");
		}, 300)
	);
	oUserName.addEventListener("blur", function(e) {
		runUserName(e, "#userName");
	});
	// password
	function runPassword(e, elSelector) {
		let value = (oPassword.value = e.target.value.trim());
		// 防止undefined输入到正则
		if (!value) {
			showFormError(elSelector, "密码为必填项");
			pageStatus.logion.password = false;
			return;
		}
		// 规则错误 :以下三种 直接为错误 ,长度在html已限制
		// 纯数字
		if (/^\d{1,}$/.test(value)) {
			showFormError(elSelector, "密码错误");
			pageStatus.logion.password = false;
			return;
		}
		// 纯字母
		if (/^[a-zA-Z]{1,}$/.test(value)) {
			showFormError(elSelector, "密码错误");
			pageStatus.logion.password = false;
			return;
		}
		// 长度小于6
		if (value.length < 6) {
			showFormError(elSelector, "密码错误");
			pageStatus.logion.password = false;
			return;
		}
		// 修改状态 / 隐藏错误信息 /隐藏登录失败
		pageStatus.logion.password = true;
		hideFormError(elSelector);
		sys.getEl(".loginError").style.display = "none";
		return true;
	}
	oPassword.addEventListener(
		"input",
		debounce(function(e) {
			runPassword(e, "#password");
		}, 300)
	);
	oPassword.addEventListener("blur", function(e) {
		runPassword(e, "#password");
	});
	// 记住我 多选框
	oRemember.addEventListener("input", e => {
		pageStatus.logion.remember = e.target.checked;
		//test
		console.table(pageStatus);
	});

	/*
	 *短信登录
	 */

	const oPhone = sys.getEl("#shortmessagePhone");
	const oSendVcode = sys.getEl("#sendVcode");
	// 机器验证框
	const oRobot_vCodeBox = sys.getEl(".robot_vCodeBox");
	// 登录框
	const oLoginBox = sys.getEl(".right.loginBox");
	function runPhone(e, elSelector) {
		// 不允许包含空格
		let value = (oPhone.value = e.target.value.trim());
		if (!value) {
			showFormError(elSelector, "手机号码为必填项");
			pageStatus.logion.phone = false;
			return;
		}
		if (!checkPhone(value)) {
			showFormError(elSelector, "手机号码格式不正确");
			pageStatus.logion.phone = false;
			return;
		}
		pageStatus.logion.phone = true;
		hideFormError(elSelector);
		sys.getEl(".loginError").style.display = "none";
		return true;
	}
	oPhone.addEventListener(
		"input",
		debounce(function(e) {
			runPhone(e, "#shortmessagePhone");
		}, 300)
	);
	oPhone.addEventListener(
		"blur",
		debounce(function(e) {
			runPhone(e, "#shortmessagePhone");
		}, 300)
	);
	// 发送验证码
	oSendVcode.addEventListener("click", () => {
		// 不是未发送状态 或者 手机号错误 直接return
		console.log(oSendVcode.countDownIng);
		if (oSendVcode.countDownIng) return;
		if (!pageStatus.logion.phone) {
			showFormError("#shortmessagePhone", "手机号码未填写或错误");
			return;
		}
		oLoginBox.style.display = "none";
		oRobot_vCodeBox.style.display = "flex";
		// 设置验证码图形
		setCodeImg();
	});
	sys.getEl("#vCode").addEventListener("input", () => {
		hideFormError(".vCodeBoxBody");
	});
	// 机器验证
	const oRobotcode_input = sys.getEl("#robotcode_input");
	const oVCodeBtn = sys.getEl("#vCodeBtn");
	const oRobotcodeErrorInfo = sys.getEl("#vCodeBtn + .errorInfo");
	const oCodeImg = sys.getEl("#codeImg");
	oRobotcode_input.addEventListener("input", e => {
		if (oRobotcode_input.value.length == 6) {
			oVCodeBtn.className = "";
			oRobotcodeErrorInfo.innerHTML = "";
		} else {
			// 长度不为6 样式为未激活/禁止点击
			oVCodeBtn.className = "vCodeBtnInactive";
		}
	});
	let iCodeDataIndex = 0;
	// 点击图片刷新
	oCodeImg.addEventListener("click", () => {
		iCodeDataIndex++;
		setCodeImg();
	});
	function setCodeImg() {
		oCodeImg.src =
			mockData.robotVcode[
				iCodeDataIndex % mockData.robotVcode.length
			].img;
	}
	iCodeDataIndex++;
	function submitVCode() {
		if (oRobotcode_input.value.length == 6) {
			// 模拟 循环取数据
			let i = iCodeDataIndex % mockData.robotVcode.length;
			let data = mockData.robotVcode[i];
			// 激活样式
			oVCodeBtn.className = "";
			// 正确 就退出机器验证 ，并发送验证码
			console.log(data, oRobotcode_input.value);
			if (data.value == oRobotcode_input.value) {
				oLoginBox.style.display = "flex";
				oRobot_vCodeBox.style.display = "none";
				// 清空
				oRobotcode_input.value = "";
				countDown("#sendVcode", 60);
				sys.getEl("#vCode").removeAttribute("disabled");
				sys.getEl("#vCode").style.background = "white";
			} else {
				oRobotcodeErrorInfo.innerHTML = "验证码错误 , 点击上方图形刷新";
			}
		} else {
			oRobotcodeErrorInfo.innerHTML = "请输入正确的验证码";
			return false;
		}
	}
	oVCodeBtn.addEventListener("click", () => {
		submitVCode();
	});
	oRobotcode_input.addEventListener("keydown", function(e) {
		if (e.keyCode === 13) {
			submitVCode();
		}
	});
	// 点击空白退出机器验证
	oRobot_vCodeBox.addEventListener("click", e => {
		// 只在自身触发
		if (e.target != oRobot_vCodeBox) return;
		oLoginBox.style.display = "flex";
		oRobot_vCodeBox.style.display = "none";
		// 清空
		oRobotcode_input.value = "";
		e.stopPropagation();
		e.preventDefault();
	});
	// 登录按钮
	oSubmitLogin.addEventListener("click", e => {
		const hash = location.hash;
		if (hash && hash != "#/") {
			if (hash == "#/signup") {
				// 注册
				return;
			} else if (hash == "#/shortmessage") {
				// 模拟登录成功数据
				if (
					pageStatus.logion.phone &&
					sys.getEl("#vCode").value.length
				) {
					window.open("https://gitee.com/");
				} else {
					pageStatus.logion.phone
						? ""
						: showFormError(
								"#shortmessagePhone",
								"手机号未填写或格式错误"
						  );
					sys.getEl("#vCode").value
						? ""
						: showFormError(".vCodeBoxBody", "验证码未填写或错误");
					return;
				}
			}
		} else {
			// 没有hash,普通登录
			// 验证是否符合规则
			let isRuleRight =
				pageStatus.logion.userName && pageStatus.logion.password;
			if (isRuleRight) {
				// 和模拟数据是否匹配
				if (
					oUserName.value == mockData.exactness.userName &&
					oPassword.value == mockData.exactness.pwd
				) {
					// 登录成功  存放token 放入请求头, 或sessionid
					window.open("https://gitee.com/");
					sys.getEl(".loginError").style.display = "none";
				} else {
					sys.getEl(".loginError").style.display = "block";
				}
			} else {
				pageStatus.logion.userName
					? ""
					: showFormError("#userName", "用户名为空或错误");
				pageStatus.logion.password
					? ""
					: showFormError("#password", "密码为空或错误");
				return;
			}
		}
	});
}

//  signup  表单 注册相关

function signupFormInit() {
	const oName = sys.getEl("#signupName");
	const oSignupDomain = sys.getEl("#signupDomain");
	const oPhoneEmail = sys.getEl("#phoneEmail");
	const oSignupVCode = sys.getEl("#signupVCode");
	const oSignupSendVcodeBtn = sys.getEl("#signupSendVcode");
	const oSignupPassword = sys.getEl("#signupPassword");
	const oAgree = sys.getEl("#agree");
	const oSubmitSignupBtn = sys.getEl("#submitSignup");
	const oEyeIcon = sys.getEl(".eyeIcon");
	function showFormError(elSelector, msg) {
		const el = sys.getEl(elSelector);
		// 对应的兄弟元素 错误提示
		let oErrorInfo = el.parentElement.parentElement.querySelector(
			".errorInfo"
		);
		oErrorInfo.style.display = "block";
		oErrorInfo.innerText = msg;
		//输入框自身变红
		if (el.tagName == "INPUT") {
			el.className = "inputError";
		}
		// 父级元素外 添加×
		if (
			el.parentElement &&
			el.parentElement.parentElement.className.indexOf("ignupRow") > -1
		) {
			el.parentElement.parentElement.className =
				"ignupRow ignupRowShowClose";
		}
	}

	function hideFormError(elSelector) {
		const el = sys.getEl(elSelector);
		let oErrorInfo = el.parentElement.parentElement.querySelector(
			".errorInfo"
		);
		oErrorInfo.style.display = "none";
		oErrorInfo.innerText = "";
		if (el.tagName == "INPUT") {
			el.className = "";
		}
		if (
			el.parentElement &&
			el.parentElement.parentElement.className.indexOf("ignupRow") > -1
		) {
			el.parentElement.parentElement.className = "ignupRow";
		}
	}
	// 各事件将要执行的函数
	function runName(e) {
		let value = oName.value.trim();
		if (!value) {
			showFormError("#signupName", "姓名为必填项");
			pageStatus.signup.name = false;
			return;
		}
		if (value.length < 2) {
			showFormError("#signupName", "最少两个字");
			pageStatus.signup.name = false;
			return;
		}
		pageStatus.signup.name = true;
		hideFormError("#signupName");
	}
	function runSignupDomain(e) {
		let value = oSignupDomain.value.trim();
		if (!value) {
			showFormError("#signupDomain", "个人空间地址为必填项");
			pageStatus.signup.domain = false;
			return;
		}
		if (!checkUserdomainName(value)) {
			showFormError(
				"#signupDomain",
				"地址只允许字母、数字或者下划线（_）、中划线（-），至少 2 个字符，必须以字母开头，不能以特殊字符结尾"
			);
			pageStatus.signup.domain = false;
			return;
		}
		pageStatus.signup.domain = true;
		hideFormError("#signupDomain");
		return true;
	}
	function runPhoneEmail(e) {
		let value = oPhoneEmail.value.trim();
		if (!value) {
			showFormError("#phoneEmail", "手机或邮箱必填");
			pageStatus.signup.phoneOrEmail = false;
			return;
		}
		let isPhoneOrEmail = checkEmail(value) || checkPhone(value);
		if (isPhoneOrEmail) {
			hideFormError("#phoneEmail");
			pageStatus.signup.phoneOrEmail = true;
			return true;
		} else {
			showFormError("#phoneEmail", "手机或邮箱格式错误");
			pageStatus.signup.phoneOrEmail = false;
			return;
		}
	}
	function runSignupVCode(e) {
		let value = oSignupVCode.value.trim();
		if (!value) {
			showFormError("#signupVCode", "验证码必填");
			pageStatus.signup.vCode = false;
			return;
		}
		hideFormError("#signupVCode");
		pageStatus.signup.vCode = true;
		return true;
	}
	// 发送验证码
	oSignupSendVcodeBtn.addEventListener("click", () => {
		// 不是未发送状态 或者 手机号错误 直接return
		console.log(oSignupSendVcodeBtn.countDownIng);
		if (oSignupSendVcodeBtn.countDownIng) return;
		if (!pageStatus.signup.phoneOrEmail) {
			showFormError(
				"#signupSendVcode",
				"手机号码或邮箱未填写，或格式错误"
			);
			return;
		}
		countDown("#signupSendVcode", 60);
		sys.getEl("#signupVCode").removeAttribute("disabled");
		sys.getEl("#signupVCode").style.background = "white";
		sys.getEl(".vCodeBoxBody #signupSendVcode + .help").style.display =
			"block";
	});
	//
	function runSignupPassword(e) {
		let value = oSignupPassword.value.trim();
		if (!value) {
			showFormError("#signupPassword", "密码为必填项");
			pageStatus.signup.password = false;
			return;
		}
		if (value.length < 6 || value.length > 32) {
			showFormError("#signupPassword", "密码的长度必须是 6-32 位");
			pageStatus.signup.password = false;
			return;
		}
		// 数字至少一次 字母或字符至少一次
		if (
			!/[0-9]{1,}[a-zA-Z\\!\@\_\#\$\%\^\&\*\(\)\-\+\=\,\.\?]{1,}/.test(
				value
			)
		) {
			showFormError(
				"#signupPassword",
				"密码必须包含数字，且必须包含字母或其它符号（!@_#$%^&*()-+=,.?）"
			);
			pageStatus.signup.password = false;
			return;
		}
		hideFormError("#signupPassword");
		pageStatus.signup.password = true;
		return true;
	}
	// 切换密码或者明文
	oEyeIcon.addEventListener("click", e => {
		if (oSignupPassword.type == "password") {
			oSignupPassword.setAttribute("type", "text");
			oEyeIcon.style.backgroundImage = "url(./img/close_eye.png)";
		} else {
			oSignupPassword.setAttribute("type", "password");
			oEyeIcon.style.backgroundImage = "url(./img/eye.png)";
		}
	});
	// 同意条款
	function runSignupAgree(e) {
		let value = oAgree.checked;
		if (!value) {
			showFormError("#agree", "请阅读并同意我们的服务条款");
			pageStatus.signup.agree = false;
			return;
		}
		hideFormError("#agree");
		pageStatus.signup.agree = true;
		return true;
	}

	// 绑定
	oName.addEventListener("input", runName);
	oName.addEventListener("blur", runName);
	oSignupDomain.addEventListener("input", runSignupDomain);
	oSignupDomain.addEventListener("blur", runSignupDomain);
	oPhoneEmail.addEventListener("input", runPhoneEmail);
	oPhoneEmail.addEventListener("blur", runPhoneEmail);
	oSignupVCode.addEventListener("input", runSignupVCode);
	oSignupVCode.addEventListener("blur", runSignupVCode);
	oSignupPassword.addEventListener("input", runSignupPassword);
	oSignupPassword.addEventListener("blur", runSignupPassword);
	oAgree.addEventListener("input", runSignupAgree);

	// 立即注册
	oSubmitSignupBtn.addEventListener("click", () => {
		// 点击时再次检测 ,(input用户未触发)
		runName();
		runSignupDomain();
		runPhoneEmail();
		runSignupVCode();
		runSignupPassword();
		runSignupAgree();
		let allTrue = Object.values(pageStatus.signup).every(item => item);
		console.log(allTrue);
		if (allTrue) {
			// 全部正确
			window.open("https://gitee.com");
		}
	});
}
